package artid.com.arttogoa.fragment;

import org.apache.commons.lang3.StringUtils;
import org.xutils.x;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import artid.com.arttogoa.R;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.BindingIbeaconBean;
import artid.com.arttogoa.parser.IbeaconActivityInfoParser;
import artid.com.arttogoa.parser.MyArtPush_IbactivityListBean;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.GsonUtils;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.util.VioceUtils;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：BindingIbeacon_Fragment   
 * 类描述   ：Ibeacon绑定页面   
 * 创建人   ：耿卫斌   
 * 创建时间：2016-11-8 下午2:12:34   
 *
 */
public class BindingIbeacon_Fragment extends Fragment implements OnClickListener{
	private View v;
	private Context mContext;
	private EditText titleEd,urlEd,addressEd,describeEd;
	private TextView resetBtn,subMitBtn;
	private ImageView headeImage0,headeImage1,voice;
	private LinearLayout notTakingPicturesLL;
	private int whichActivity=0;//默认我的出售 （0：个人微站 1：自定义推广活动）
	private MyArtPush_IbactivityListBean mMyArtPush_IbactivityListBean;//用于提交数据的时候获取id
	private IbeaconActivityInfoParser mIbeaconActivityInfoParser;//编辑时要获取的数据
	private String action="新建";//默认动作为新建
	private String Bitmap64;// 剪裁之后的图片流
	private String PhotoPath;//剪裁之后的图片地址
	private Bitmap mBitmap0,mBitmap1;//保存个人、自定义请求到的活动图片
	private ImageLoader mImageLoader;
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v=inflater.inflate(R.layout.fragment_bindingibeacon, null);
		initView();
		return v;
	}

	public BindingIbeacon_Fragment(int whichActivity,String action,
			MyArtPush_IbactivityListBean mMyArtPush_IbactivityListBean,
			IbeaconActivityInfoParser mIbeaconActivityInfoParser) {
		super();
		this.whichActivity = whichActivity;
		this.action = action;
		this.mMyArtPush_IbactivityListBean = mMyArtPush_IbactivityListBean;
		this.mIbeaconActivityInfoParser = mIbeaconActivityInfoParser;
	}

	@SuppressLint("NewApi") private void initView(){
		mContext=getActivity();
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.BindingIbeacon_Fragment.receiver");
		getActivity().registerReceiver(broadcastReceiver, filter);
		headeImage0=(ImageView) v.findViewById(R.id.BindingIbeacon_Fragment_headeImage0);
		headeImage1=(ImageView) v.findViewById(R.id.BindingIbeacon_Fragment_headeImage1);
		headeImage1.setOnClickListener(this);
		notTakingPicturesLL=(LinearLayout) v.findViewById(R.id.BindingIbeacon_Fragment_notTakingPictures);
		notTakingPicturesLL.setOnClickListener(this);
		titleEd=(EditText) v.findViewById(R.id.BindingIbeacon_Fragment_title);
		titleEd.addTextChangedListener(mTextChangedListener);
		urlEd=(EditText) v.findViewById(R.id.BindingIbeacon_Fragment_url);
		urlEd.addTextChangedListener(mTextChangedListener);
		addressEd=(EditText) v.findViewById(R.id.BindingIbeacon_Fragment_address);
		addressEd.addTextChangedListener(mTextChangedListener);
		describeEd=(EditText) v.findViewById(R.id.BindingIbeacon_Fragment_describe);
		describeEd.addTextChangedListener(mTextChangedListener);
		voice=(ImageView) v.findViewById(R.id.iv_vioce);
		voice.setOnClickListener(this);
		resetBtn=(TextView) v.findViewById(R.id.BindingIbeacon_Fragment_resetBtn);
		resetBtn.setOnClickListener(this);
		subMitBtn=(TextView) v.findViewById(R.id.BindingIbeacon_Fragment_subMitBtn);
		subMitBtn.setOnClickListener(this);
		subMitBtn.setEnabled(false);
		subMitBtn.setBackgroundResource(R.drawable.bg_huise);
		RequestQueue mQueue = Volley.newRequestQueue(getActivity());
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		if("编辑".equals(action)){
			EditAssignment();
		}
		//设置UI
		if(whichActivity==0){
			voice.setVisibility(View.GONE);
			titleEd.setFocusable(false);
			urlEd.setFocusable(false);
			describeEd.setFocusable(false);
		}else if(whichActivity==1){
			voice.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.BindingIbeacon_Fragment_notTakingPictures:
			//设置推广图片
			if(whichActivity==1){
				Intent intent0 = new Intent("com.BindingIbeacon_Activity.receiver");  
				intent0.putExtra("Photo", true);
				mContext.sendBroadcast(intent0);
			}
			break;
		case R.id.BindingIbeacon_Fragment_headeImage1:
			//设置推广图片
			if(whichActivity==1){
				Intent intent0 = new Intent("com.BindingIbeacon_Activity.receiver");  
				intent0.putExtra("Photo", true);
				mContext.sendBroadcast(intent0);
			}
			break;
		case R.id.iv_vioce:
			VioceUtils vu = new VioceUtils(getActivity(), voice, describeEd);
			vu.init();
			break;
		case R.id.BindingIbeacon_Fragment_resetBtn:
			//重置
			if(whichActivity==0){
				//个人微站
				addressEd.setText("");
			}else if(whichActivity==1){
				//自定义推广活动
				notTakingPicturesLL.setVisibility(View.VISIBLE);
				headeImage1.setVisibility(View.GONE);
				Bitmap64="";
				titleEd.setText("");
				titleEd.setText("");
				urlEd.setText("");
				addressEd.setText("");
				describeEd.setText("");
			}
			break;
		case R.id.BindingIbeacon_Fragment_subMitBtn:
			//确定
			postData();
			break;

		default:
			break;
		}
	}

	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			conditionJudgment();
		}  
	};  

	/**
	 * 条件判断
	 */
	private void conditionJudgment(){
		Boolean isBitmap64=true;
		if("新建".equals(action) && whichActivity==1 && StringUtils.isEmpty(Bitmap64)){
				isBitmap64=false;
		}
		if(	!StringUtils.isEmpty(titleEd.getText().toString()) && 
				!StringUtils.isEmpty(urlEd.getText().toString()) && 
				!StringUtils.isEmpty(describeEd.getText().toString()) && isBitmap64){
			subMitBtn.setEnabled(true);
			subMitBtn.setBackgroundResource(R.drawable.verification_code_check);
		}else{
			subMitBtn.setEnabled(false);
			subMitBtn.setBackgroundResource(R.drawable.bg_huise);
		}
	}

	/**
	 * 编辑自定义赋值
	 */
	private void EditAssignment(){
		downloadImage(mIbeaconActivityInfoParser.getIbactivityimage(),whichActivity);
		titleEd.setText(mIbeaconActivityInfoParser.getIbactivitytitle());
		urlEd.setText(mIbeaconActivityInfoParser.getIbactivityurl());
		addressEd.setText(mIbeaconActivityInfoParser.getIbactivityaddress());
		describeEd.setText(mIbeaconActivityInfoParser.getIbactivitycontent());
	}
	
	/**
	 * 新建个人微站赋值
	 */
	private void EditePersonalMicroStation(){
		downloadImage(AppUtil.getUser().getAvatarurl(),whichActivity);
		titleEd.setText(AppUtil.getUser().getRealname()+"的个人微站");
		urlEd.setText(Cache.shardPersonWeiZhan+ AppUtil.getUser().getUid());
		addressEd.setText("");
		describeEd.setText(AppUtil.getUser().getRealname()+"的个人微站");
	}

	/**
	 * 第一次绑定
	 */
	private void newBinding(){
		if(whichActivity==0){
			headeImage0.setVisibility(View.VISIBLE);
			headeImage1.setVisibility(View.GONE);
			EditePersonalMicroStation();
			if(mBitmap0!=null){
				headeImage0.setImageBitmap(mBitmap0);
			}
		}else if(whichActivity==1){
			if(!StringUtils.isEmpty(Bitmap64)){
				headeImage0.setVisibility(View.GONE);
				headeImage1.setVisibility(View.VISIBLE);
				headeImage1.setImageBitmap(mBitmap1);
			}else{
				notTakingPicturesLL.setVisibility(View.VISIBLE);
				headeImage1.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 读取图片
	 */
	private void downloadImage(String imageUrl,final int whichActivity){
		if (!StringUtils.isEmpty(imageUrl)) {
			mImageLoader.get(imageUrl,new ImageListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					// TODO Auto-generated method stub

				}
				@Override
				public void onResponse(ImageContainer response,
						boolean isImmediate) {
					// TODO Auto-generated method stub
					if(whichActivity==0){
						headeImage0.setVisibility(View.VISIBLE);
						headeImage1.setVisibility(View.GONE);
						headeImage0.setImageResource(R.drawable.personal_normal);
						mBitmap0 = response.getBitmap();
					}else if(whichActivity==1){
						mBitmap1 = response.getBitmap();
					}
					if(mBitmap0!=null){
						notTakingPicturesLL.setVisibility(View.GONE);
						headeImage0.setVisibility(View.VISIBLE);
						headeImage0.setImageBitmap(mBitmap0);
					}else if(mBitmap1!=null){
						notTakingPicturesLL.setVisibility(View.GONE);
						headeImage1.setVisibility(View.VISIBLE);
						headeImage1.setImageBitmap(mBitmap1);
					}
				}
			});
		}
	}

	/**
	 * 艺术家绑定ibeacon活动 新加/编辑
	 * 口令token	
    	活动id	     ibactivityid	
		ibeacon的id	      ibeaconid	
		活动名字	      ibactivitytitle	
		活动图片	      ibactivityimage	Base64数据流
		活动url	      ibactivityurl	
		活动地点	     ibactivityaddress	
     	活动描述	     ibactivitycontent	
     	类型	      type	1为个人微站，2为自定义
	 */
	private void postData(){
		String type="1";//默认为个人微站
		if(whichActivity==0){
			type="1";
		}else{
			type="2";
		}
		VolleyBasic.showLoding(getActivity());
		RequestParams params=new RequestParams(Cache.ibactivityOperation);
		params.addHeader("Accept",  "application/json, text/javascript, */*");
		params.addParameter("token", AppUtil.getUser().getToken());
		if(mBitmap0!=null && whichActivity==0 && "新建".equals(action)){
			//微站新建图
			params.addParameter("is_url", "1");
			params.addParameter("ibactivityimage", BitmapUtil.bitmaptoString(mBitmap0));
		}else if(!StringUtils.isEmpty(Bitmap64) && whichActivity==1){
			//自定义新建/编辑绑定信息
			params.addParameter("is_url", "1");
			params.addParameter("ibactivityimage", Bitmap64);
		}else{
			//编辑不改变图
			params.addParameter("is_url", "2");
			params.addParameter("ibactivityimage", "");
		}
		if("新建".equals(action)){
			params.addParameter("ibactivityid", "");
		}else if("编辑".equals(action)){
			params.addParameter("ibactivityid", mMyArtPush_IbactivityListBean.getIbactivityid());
		}
		params.addParameter("ibeaconid", mMyArtPush_IbactivityListBean.getIbeaconid());
		params.addParameter("ibactivitytitle", titleEd.getText().toString());
		params.addParameter("ibactivityurl", urlEd.getText().toString());
		params.addParameter("ibactivityaddress", addressEd.getText().toString());
		params.addParameter("ibactivitycontent", describeEd.getText().toString());
		params.addParameter("type", type);
		params.setConnectTimeout(60000);
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				System.out.println("主动停止网络请求");
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				//请求错误
				System.out.println("ex异常信息不是来自回调方法："+ex.toString());
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				System.out.println("请求完毕,不管成功失败");
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				//成功
				VolleyBasic.disMissLoding();
				Log.d("log", "Post请求结果："+result);
				String code=GsonUtils.message(result, "ret");
				String message=GsonUtils.message(result, "msg");
				if("1".equals(code)){
					BindingIbeaconBean bean=GsonUtils.json2bean(result, BindingIbeaconBean.class);
					if(bean.getData().getStatus()==1){
						//请求成功之后删除剪裁图片
						if(!StringUtils.isEmpty(Bitmap64)){
							BitmapUtil.deleteBitmap(PhotoPath);
						}
						//通知艺推列表刷新
						Intent intent0 = new Intent("com.MyArtPush_Activity.receiver");  
						intent0.putExtra("isRefresh",true);
						mContext.sendBroadcast(intent0);
						//通知艺推详情刷新
						Intent intent1 = new Intent("com.IbeaconActivityInfo_Activity.receiver");  
						intent1.putExtra("isRefresh",true);
						intent1.putExtra("ibactivityid",mMyArtPush_IbactivityListBean.getIbactivityid());
						mContext.sendBroadcast(intent1);
						getActivity().finish();
					}else{
						ToastUtil.toast(mContext, message);
					}
				}else if("0".equals(code)){
					ToastUtil.toast(getActivity(), message);
				}else if("-99".equals(code)){
					VolleyBasic.showRemoteLoginDialog(getActivity());
				}
			}
		});

	}


	// 对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getBooleanExtra("Photo", false) == true) {
				//判断是否是由拍照或者获取本地图片
				PhotoPath=intent.getStringExtra("PhotoPath");
				mBitmap1 = BitmapUtil.getSmallFilletBitmap(PhotoPath,500, 500);
				notTakingPicturesLL.setVisibility(View.GONE);
				headeImage1.setVisibility(View.VISIBLE);
				headeImage1.setImageBitmap(mBitmap1);
				Bitmap64 = BitmapUtil.bitmaptoString(mBitmap1);
				conditionJudgment();
				//当网络请求成功之后删除剪裁之后的图片
			}
		}
	};

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		//销毁广播
		mContext.unregisterReceiver(broadcastReceiver);
	}



	/**
	 * 防止控件没加载出来报空
	 */
	private void getDatas(){
		if(v!=null){
			if("新建".equals(action)){
				newBinding();
			}
		}else{
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					if(v!=null){
						getDatas();
					}
				}
			}, 1000);
		}
	}

	/**
	 * 每次切换Fragment刷新页面
	 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		// 每次切换fragment时调用的方法
		if (isVisibleToUser) {
			getDatas();
		}
	}

}
